<?php

namespace App\Service\Customer;
use App\Models\Customer\CustomerTokenModel;
use DB;

class CustomerTokenService
{

    /**
     * 记录token
     * @param string $uid
     * @return array|bool
     */
    public static function generate($uid = "")
    {
        $nowtime = time();
        $token = substr(md5($uid . $nowtime), 8, 16);
        $expire = $nowtime + 7200;
        return self::setToken($uid, $token, $expire) ? ['token' => $token, "uid" => $uid, "expire" => $expire] : false;
    }
    /**
     * 设置用户token
     * @param $uid
     * @param $token
     * @param $token_expire
     * @return mixed
     */
    public static function setToken($uid, $token, $token_expire)
    {
        $sql = "INSERT INTO lsj_user_token(uid,token,token_expire) 
                VALUES(?, ?, ?) 
                ON DUPLICATE KEY UPDATE uid=?,token=?,token_expire=?";
        $result = DB::insert($sql,[$uid,$token,$token_expire,$uid,$token,$token_expire]);
        return $result;
    }

    /**
     * 检验token
     */
    public static function valid($uid = "", $token = "")
    {
        $result = CustomerTokenModel::where(['uid' => $uid, 'token' => $token])->first();
        return $result;
    }

    /**
     * 获得 token
     */
    public static function getToken($uid = "")
    {
        $result = CustomerTokenModel::where('uid',$uid)->first();
        return $result;
    }
}